<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="display: inline-block">
        <div>
          <a-form size="small" :model="pageData" layout="inline" label-align="right" :label-col-props="{ span: 8 }"
            :wrapper-col-props="{ span: 16 }">
            <a-form-item label="转移单号" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input class="bacClass" v-model="pageData.materialTurnCode" @press-enter="huiche" allow-clear
                style="width: 200px" />
            </a-form-item>

            <a-form-item label="原料编号" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input class="bacClass" v-model="pageData.rawmaterialCode" @press-enter="huiche" allow-clear
                style="width: 200px" />
            </a-form-item>

            <a-form-item label="原料名称" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input class="bacClass" v-model="pageData.rawmaterialName" @press-enter="huiche" allow-clear
                style="width: 200px" />
            </a-form-item>

            <a-form-item label="纱批" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input class="bacClass" v-model="pageData.yarnBatch" @press-enter="huiche" allow-clear
                style="width: 200px" />
            </a-form-item>

            <a-form-item label="日期" :style="{ width: '345px' }" label-col-flex="100px">
              <a-date-picker popup-container="html" class="bacClass" v-model="pageData.dateStart" />
            </a-form-item>
            <a-form-item :style="{ width: '345px' }" label-col-flex="100px" label="至">
              <a-date-picker popup-container="html" class="bacClass" v-model="pageData.dateEnd" />
            </a-form-item>

            <a-form-item label="单据状态" :style="{ width: '345px' }" label-col-flex="100px">
              <a-select popup-container="html" class="bacClass" :allowClear="true" v-model="pageData.auditState"
                :filter-option="false" allow-search style="width: 200px">
                <a-option :value="0">未提交</a-option>
                <a-option :value="1">已提交</a-option>
                <a-option :value="2">已作废</a-option>
              </a-select>
              <!-- <a-input class="bacClass" v-model="pageData.customName" @press-enter="huiche" allow-clear
                style="width: 200px" /> -->
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="pageData.btnList" @select="selectHandler" @cel="zuofei" @tj="tjs" @export="exports"
          @del="deleteHandler">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-space style="float: right; z-index: 9999"> </a-space>

      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady"
        @columnResized="onColumnResized" @columnMoved="onColumnMoved" @columnVisible="onColumnVisible"
        style="height: calc(100% - 45px);" :defaultColDef="defaultColDef" class="ag-theme-alpine"
        :rowData="table.dataList" :columnDefs="tc1" :localeText="localeText1">
      </AgGridVuesCopys>
      <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize"
        @page-size-change="change1" style="justify-content: center" :page-size="pagination.pageSize"
        :current="pagination.page" :page-size-options="pagingList1" />
    </template>

    <a-drawer :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
      unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false" cancel-text="关闭" ok-text="保存">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form ref="formRef" layout="horizontal" :model="dataForm">
            <a-form-item label-col-flex="80px" label="整件件数">
              <a-input-number class="bacClass" v-model="dataForm.pieceNum" :precision="2" />
            </a-form-item>
            <a-form-item label-col-flex="80px" label="散件件数">
              <a-input-number class="bacClass" v-model="dataForm.bulkNum" :precision="2" />
            </a-form-item>
            <a-form-item label-col-flex="80px" label="散件散重">
              <a-input-number class="bacClass" v-model="dataForm.bulkWeight" :precision="2" />
            </a-form-item>
          </a-form>
        </a-form>
      </div>
    </a-drawer>

    <a-modal v-model:visible="showModal" :width="360" title="提交" class="modal-dialog-wrapper">
      <slot name="content">
        <a-form-item label="仓库" :style="{ width: '320px' }" label-col-flex="70px">
          <a-select popup-container="html" class="bacClass" :style="{ width: '230px' }" v-model="warehouseId">
            <a-option v-for="item in WarehouseList" :key="item.id" :value="item.id">{{ item.warehouseName }}</a-option>
          </a-select>
        </a-form-item>
      </slot>
      <template #footer>
        <a-space>
          <a-button @click="showModal = false">关闭</a-button>
          <a-button type="primary" @click="onConfirm">保存</a-button>
        </a-space>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import QrcodeVue from 'qrcode.vue'
import ModalDialog from '@/components/ModalDialog.vue'
import { ref, reactive, onMounted, onActivated } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import emitter from '@/hooks/useEventBus'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { EXELTABLE } from '@/utils/exportEXCEL';
import usePermission from '@/store/modules/permission'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
interface ClothInfo {
  id: any
  pieceNum: any
  bulkNum: any
  bulkWeight: any
}

export default {
  name: 'WorkshopMaterialTransferDemo',
  setup() {
    const dataForm = reactive<ClothInfo>({
      id: null,
      pieceNum: '',
      bulkNum: '',
      bulkWeight: '',
    })
    const headerShow = ref<boolean>(true)
    const total = ref(10)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }
    let id = ref(1)
    //查询

    function doRefresh() {
      pageData.pageLoading = true
      updateGridState01()
      post({
        url: '/qms/MaterialTurn/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: 0,
          materialTurnCode: pageData.materialTurnCode,
          auditState: pageData.auditState === 0 ? 0 : !pageData.auditState ? undefined : pageData.auditState,
          rawmaterialCode: pageData.rawmaterialCode,
          rawmaterialName: pageData.rawmaterialName,
          yarnBatch: pageData.yarnBatch,
          beginDate: pageData.dateStart,
          endDate: pageData.dateEnd,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            // data.list.filter(function(o:any){

            // })
            table.handleSuccess(data.list)
            gridOption.value.setRowData(data.list)
            total.value = data.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    const huiche = () => {
      doRefresh()
    }
    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const selectedRowKeysChecked = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const table1 = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '公司',
        key: 'outSouringCompany',
        dataIndex: 'outSouringCompany',
        width: 150,
      },
      {
        title: '转移单号',
        key: 'materialTurnCode',
        dataIndex: 'materialTurnCode',
        width: 150,
      },
      {
        title: '转出织布单号',
        key: 'outPlanOrderCode',
        dataIndex: 'outPlanOrderCode',
        width: 150,
      },
      {
        title: '转出客户',
        key: 'outCustomName',
        dataIndex: 'outCustomName',
        width: 150,
      },
      {
        title: '转出机台号',
        key: 'outMachineCode',
        dataIndex: 'outMachineCode',
        width: 150,
      },
      {
        title: '转入织布单号',
        key: 'inPlanOrderCode',
        dataIndex: 'inPlanOrderCode',
        width: 150,
      },
      {
        title: '转入客户',
        key: 'inCustomName',
        dataIndex: 'inCustomName',
        width: 150,
      },
      {
        title: '转入机台号',
        key: 'inMachineCode',
        dataIndex: 'inMachineCode',
        width: 150,
      },

      {
        title: '原料编号',
        key: 'rawmaterialCode',
        dataIndex: 'rawmaterialCode',
        width: 150,
      },

      {
        title: '原料名称',
        key: 'rawmaterialName',
        dataIndex: 'rawmaterialName',
        width: 150,
      },
      {
        title: '纱批',
        key: 'yarnBatch',
        dataIndex: 'yarnBatch',
        width: 200,
      },

      {
        title: '等级',
        key: 'grade',
        dataIndex: 'grade',
        width: 200,
      },
      {
        title: '转移重量',
        key: 'turnNum',
        dataIndex: 'turnNum',
        width: 200,
      },
      {
        title: '整件件数',
        key: 'pieceNum',
        dataIndex: 'pieceNum',
        width: 200,
      },
      {
        title: '整件件重',
        key: 'pieceWeight',
        dataIndex: 'pieceWeight',
        width: 200,
      },

      {
        title: '散件件数',
        key: 'bulkNum',
        dataIndex: 'bulkNum',
        width: 200,
      },
      {
        title: '散件散重',
        key: 'bulkWeight',
        dataIndex: 'bulkWeight',
        width: 200,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },

      {
        title: '单据状态',
        key: 'auditState',
        slotName: 'act1',
        width: 150,
        fixed: 'right',
      },
      {
        title: '操作',
        key: 'act',
        slotName: 'act',
        width: 80,
        fixed: 'right',
      },
    ])

    //获取公司部门组列表
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }

    let tc1: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'act1') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 100
        obj['lockPosition'] = 'right'
        obj['cellRenderer'] = {
          template: `<el-tag class="ml-2" v-if="a == 0" type="warning">未提交</el-tag>
          <el-tag class="ml-2" v-if="a == 1" type="success">已提交</el-tag>
          <el-tag class="ml-2" v-if="a == 2" type="info">作废</el-tag>`,
          setup(props: any) {
            let val = ref()
            val.value =
              props.params.data.auditState == 0
                ? '未提交'
                : props.params.data.auditState == 1
                  ? '已提交'
                  : '作废'
            return {
              val,
              a: props.params.data.auditState,
            }
          },
        }
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `<a-space><el-button style="color:#165dff;" @click="a" class="gesture" link v-if="f">修改</el-button></a-space>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            let f = permissionStore.hasPermisson('cjzlcx.xg')
            return {
              a,
              ainfo: props.params.data,
              f,
            }
          },
        }
      }

      return obj
    })
    let a1 = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc1 = a1.concat(tc1)

    const pageData = reactive<{
      pageLoading: boolean
      customName: any
      rawmaterialCode: any
      rawmaterialName: any
      yarnBatch: any
      dateStart: any
      dateEnd: any
      materialTurnCode: any
      rHeight: number | undefined
      showAdd: boolean
      sideTitle: string
      btnList: any[],
      auditState: any
    }>({
      sideTitle: '修改',
      pageLoading: false,
      materialTurnCode: '',
      customName: '',
      rawmaterialCode: '',
      rawmaterialName: '',
      yarnBatch: '',
      dateStart: '',
      dateEnd: '',
      rHeight: 0,
      showAdd: false,
      btnList: [],
      auditState: ''
    })

    onMounted(() => {
      doRefresh()
      emitter.on('WorkshopMaterialTransferDemo', () => {
        // selCxAll({});
        doRefresh()
      })
      pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 50
      }
    })
    let isIDs: any = ref(1)

    // 查询按钮事件
    const selectHandler = () => {
      pagination.page = 1
      loadings.value = true
      doRefresh()
    }

    let loadings = ref(false)
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: '/qms/MaterialTurn/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          }).then(({ code, data, message }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })

              pagination.page = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
        },
      })
    }

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }
    const whList = ref<any[]>([])
    const whService = new WHService()
    const whTypeList = whService.whTypeList
    const whTypeFieldList = whService.whTypeFieldList
    const companyList: any = whService.companyList

    const editHandler = (record: any) => {
      for (var key in record) {
        dataForm[key] = record[key]
      }
      if (record.auditState == 0) {
        pageData.showAdd = true
      }

    }
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      post({
        url: '/qms/MaterialTurn/update',
        data: [dataForm],
      }).then((res: any) => {
        if (res.code === 200) {
          formRef.value?.resetFields()
          pageData.showAdd = false

          Message.success({
            content: '修改成功',
            duration: 5000,
          })
          doRefresh()
        } else {
          Message.error({
            content: res.message,
            duration: 5000,
          })
        }
      })
    }

    // 作废事件
    const zuofei = () => {
      // alert(999)
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      if (gridOption.value.getSelectedRows().map((o: any) => {
        return o.auditState
      })[0] != 2) {
        if (gridOption.value.getSelectedRows().map((o: any) => {
          return o.auditState
        })[0] != 1) {
          Modal.confirm({
            title: '系统提示',
            content: '确认作废选中的数据?',
            onOk() {
              pageData.pageLoading = true
              post({
                url: '/qms/MaterialTurn/update',
                data: [
                  {
                    id: gridOption.value.getSelectedRows().map((o: any) => {
                      return o.id
                    })[0],
                    auditState: 2,
                  },
                ],
              })
                .then(({ code, data }: any) => {
                  if (code === 200) {
                    Message.success({
                      content: '修改成功',
                      duration: 6000,
                    })
                    pagination.page = 1
                    doRefresh()
                  } else {
                    Message.error({
                      content: '修改失败',
                      duration: 6000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            },
          })
        } else {
          Message.error({
            content: '数据已提交无法再次作废！',
            duration: 6000,
          })
        }

      } else {
        Message.error({
          content: '数据已作废无法再次作废！',
          duration: 6000,
        })
      }
    }

    const WarehouseList = ref([])
    const warehouseId = ref('')
    const showModal = ref(false)
    const onConfirm = () => {
      if (!warehouseId.value) {
        Message.error('请选择仓库')
        return
      }
      const rowSelection = gridOption.value.getSelectedRows()
      const findItem = WarehouseList.value.find((item: any) => item.id == warehouseId.value)
      let params = JSON.parse(JSON.stringify(rowSelection))

      if (findItem) {
        params.forEach((item: any) => {
          item.auditState = 1
          item.firmId = item.outSouringCompanyId
          item.firmName = item.outSouringCompany

          item.warehouseName = findItem.warehouseName
          item.warehouseId = warehouseId.value
        })
      }
      MaterialTurnState(params)
    }

    // 提交事件
    const tjs = () => {
      const rowSelection = gridOption.value.getSelectedRows()
      if (rowSelection.length === 0) {
        Message.error('请先勾选')
        return
      }
      const firstCompany = rowSelection[0].outSouringCompany
      const isOutSouringCompany = rowSelection.every((item) => firstCompany == item.outSouringCompany);

      if (!isOutSouringCompany) {
        Message.error('请选择同一公司')
        return
      }

      const zt = rowSelection.every((item) => item.auditState == 0);
      if (!zt) {
        Message.error('数据已提交无法再次提交！')
        return
      }

      const isOrderCode = rowSelection.some((item) => item.inPlanOrderCode != item.outPlanOrderCode);
      if (isOrderCode) {
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: {
            warehouseTypeName: '原纱仓',
            firmId: rowSelection[0].outSouringCompanyId,
            virtuallyState: 0,
          },
        }).then(({ data, code }) => {
          if (code === 200) {
            WarehouseList.value = data
            if(WarehouseList.value.length > 0 ){
              warehouseId.value = WarehouseList.value[0].id
            }else {
              warehouseId.value ='';
            }
            showModal.value = true
          }
        })
      } else {
        const params = JSON.parse(JSON.stringify(rowSelection))
        params.forEach((item: any) => {
          item.auditState = 1
          item.firmId = item.outSouringCompanyId
          item.firmName = item.outSouringCompany
        });
        Modal.confirm({
          title: '系统提示',
          content: '确认提交选中的数据?',
          onOk() {
            MaterialTurnState(params)
          },
        })
      }
    }

    const MaterialTurnState = async (params) => {

      pageData.pageLoading = true
      post({
        url: '/qms/MaterialTurn/update',
        data: params
      })
        .then(({ code, data,message }: any) => {
          if (code === 200) {
            if (showModal.value) showModal.value = false
            Message.success({
              content: '提交成功',
              duration: 6000,
            })
            pagination.page = 1
            doRefresh()
          } else {
            Message.error({
              content: message,
              duration: 6000,
            })
          }
        })
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    //导出
    const exports = () => {
      post({
        url: '/qms/MaterialTurn/getExportExcel',
        data: {
          deleteState: 0,
          materialTurnCode: pageData.materialTurnCode,
          auditState: pageData.auditState,
          rawmaterialCode: pageData.rawmaterialCode,
          rawmaterialName: pageData.rawmaterialName,
          yarnBatch: pageData.yarnBatch,
          beginDate: pageData.dateStart,
          endDate: pageData.dateEnd,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            EXELTABLE(tc1, data, '转料汇总')
          }
        })
    }
    const pagingList1: any = ref(pagingList)
    const localeText1: any = ref(localeText)
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('cjzlcx.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('cjzlcx.xz')) {
      pageData.btnList.push('新增')
    }
    // if (permissionStore.hasPermisson('cjzlcx.sc')) {
    //   pageData.btnList.push('删除')
    // }
    if (permissionStore.hasPermisson('cjzlcx.dc')) {
      pageData.btnList.push('导出')
    }
    if (permissionStore.hasPermisson('cjzlcx.tj')) {
      pageData.btnList.push('提交')
    }
    if (permissionStore.hasPermisson('cjzlcx.zf')) {
      pageData.btnList.push('作废')
    }
    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('WorkshopMaterialTransferDemo-1', gridOption, colState, tc1)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    const onColumnVisible = () => {
      saveGridState01()
    }
    return {
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      onColumnVisible,
      colState,
      pagingList1,
      localeText1,
      huiche,
      editHandler,
      print,
      whTypeList,
      isIDs,
      companyList,
      table1,
      whList,
      zuofei,
      id,
      exports,
      tc1,
      gridOption,
      deleteHandler,
      gridReady,
      sideOk,
      total,
      dataForm,
      selectedRowKeys,
      s: selectedRowKeysChecked.selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      selectHandler,
      defaultColDef,
      tjs,
      headerShow,
      change1,
      PageSize,
      MaterialTurnState,
      WarehouseList,
      warehouseId,
      showModal,
      onConfirm
    }
  },
  components: { Toolbar, PageTabelLayout, ModalDialog, QrcodeVue },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>
